/**
 * created by 小卷毛, 2021-07-14
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl.ui.report_023

import com.google.android.material.tabs.TabLayout
import com.lzg.extend.BaseResponse
import com.lzg.extend.jackson.JacksonConvert
import com.lzg.okrx.RxSingleHelper
import com.lzg.okrx.adapter.FlowableBody
import com.lzy.okgo.OkGo
import com.rzico.sbl.R
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report_0537.QFOrderFooter
import com.rzico.sbl.ui.report_0537.QFOrderHeader
import com.rzico.sbl.ui.report_0537.QFOrderModel
import com.rzico.sbl.viewmodel.DialogViewModel
import com.xinnuo.common.extend.find
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.applyFlowableSchedulers
import com.xinnuo.common_ui.utils.applySchedulers
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.common_ui.view.BadgeTextView

/**
 * 描 述：曲阜报货订单操作相关
 * 作 者：小卷毛  2021-07-14 09:44
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class CQReportOrderViewModel : DialogViewModel() {

    /**
     * 获取订单列表
     */
    fun orderList(
        page: Int,
        state: String,
        keyWord: String,
        beginDate: String,
        endDate: String,
        onSuccess: (ArrayList<Any>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.post<BaseResponse<QFOrderModel>>(ReportUrl.getBaseUrl().rptOrder)
            .isMultipart(true)
            .params(
                getParams(
                    "status" to state,
                    "searchValue" to keyWord,
                    "beginDate" to beginDate,
                    "endDate" to endDate,
                    "pageStart" to page * 10,
                    "pageSize" to 10
                )
            )
            .converter(object : JacksonConvert<BaseResponse<QFOrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map {
                ArrayList<Any>().apply {
                    it.data.data.forEachIndexed { index, item ->
                        // 添加Header
                        add(QFOrderHeader().apply {
                            position = index
                            orderSN = item.sn
                            status = item.status
                            status_hint = item.statusDescr
                            hint = "下单时间: "
                            time = item.createDate.getTimeString()
                        })

                        // 添加商品
                        addItems(
                            item.orderItems.onEach {
                                it.orderSN = item.sn
                                it.status = item.status
                                it.position = index
                                it.methodDescr = item.methodDescr.orEmpty()
                            }
                        )

                        // 添加Footer
                        add(QFOrderFooter().apply {
                            position = index
                            orderSN = item.sn
                            shippingSn = item.shippingSn.orEmpty()
                            status = item.status
                            total_num = item.quantity
                            amount = item.amount.orEmpty()
                            name = item.consignee.orEmpty()
                            phone = item.phone.orEmpty()
                            address = item.address
                            memo = item.memo.orEmpty()
                            adminName = item.adminName.orEmpty()
                            createDate = item.createDate.getTimeString()
                            hopeDate = item.hopeDate.getTimeString()
                            methodDescr = item.methodDescr.orEmpty()
                            printStatus = item.printStatus.orEmpty()

                            rejectMemo =
                                when (status) {
                                    "unpaid", "rejected" -> item.rejectMemo.orEmpty()
                                    else -> ""
                                }

                            when (status) {
                                "unpaid" -> {
                                    hint_btn1 = "确认"
                                    hint_btn2 = "取消"
                                }
                                "unshipped" -> hint_btn1 = "派单"
                                "shipped" -> hint_btn1 = "转派"
                                "revoked" -> {
                                    hint_btn1 = "转派"
                                    hint_btn2 = "取消"
                                }
                            }
                        })
                    }
                }
            }
            .subscribeByFinally(
                event = this,
                onSuccess = { onSuccess(it) },
                onFinally = { onFinally() }
            )
    )

    /**
     * 订单数量
     */
    fun orderCount() =
        RxSingleHelper.requestString(
            url = ReportUrl.getBaseUrl().reportCut,
            params = getParams("type" to "1")
        )
            .compose(applySchedulers())
            .doOnSubscribe { }
            .doFinally { }

    /**
     * 更新办公室自定义Tab数量
     */
    fun updateFinanceNum(
        unpaid: String,
        unshipped: String,
        revoked: String,
        shipped: String,
        layout: TabLayout
    ) {
        layout.getTabAt(1)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(unpaid)
        }
        layout.getTabAt(2)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(unshipped)
        }
        layout.getTabAt(3)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(revoked)
        }
        layout.getTabAt(4)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(shipped)
        }
    }

    /**
     * 确认派单
     */
    fun shipOrder(
        orderSN: String,
        shopId: String,
    ) = RxSingleHelper.requestString(
        url = ReportUrl.getBaseUrl().rptShip,
        params = getParams(
            "sn" to orderSN,
            "shopId" to shopId,
            "shippingMethod" to "warehouse"
        )
    )
        .compose(applySchedulers())
        .doOnSubscribe { showLoading() }
        .doFinally { dismissLoading() }

}